package com.hstc.db;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @auther 倪万佳
 * @date 2018/11/6 8:52
 */
public class DbFactory
{
    public static Connection getConnection()
    {
        Connection conn = null;
        try
        {
            Context ctx = new InitialContext();
            if (ctx == null)
            {
                throw new Exception("No Context");
            }
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DBPool");
            if (ds != null)
            {
                conn = ds.getConnection();
            }
        }
        catch (NamingException e)
        {
            e.printStackTrace();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 此方法是公共方法，专门用来关闭数据库资源
     * @param rs
     * @param pstmt
     * @param con
     */
    public static void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con){
        try {
            if(rs!=null){
                rs.close();
            }if(pstmt!=null){
                pstmt.close();
            }if(con!=null){
                con.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}
